import type { EmissionFactorBody } from '@/api/modules/emissionFactors'
import type { TableColumn } from '@/types'
import { PAGING } from '@/constant'

import { carbonEmissionFactorApi } from '@/api'

export default function useTableLists() {
  const columns = shallowRef<TableColumn<EmissionFactorBody>[]>([
    { key: uuid(), type: 'selection' },
    { key: uuid(), label: '能源品种', prop: 'energyName' },
    { key: uuid(), label: '能源编码', prop: 'energyCode' },
    { key: uuid(), label: '起始日期', prop: 'startTime' },
    { key: uuid(), label: '排放因子', prop: 'emissionFactors' },
    { key: uuid(), label: '因子单位', prop: 'unit' },
  ])
  const [loading, setLoading] = useState(false)
  const [tableData, setTableData] = useShallowState<EmissionFactorBody[]>([])
  const pagination = reactive({
    pageNumber: 1,
    pageSize: PAGING.PAGE_SIZES[0]!,
    total: 0,
  })

  async function confirmDel() {
    return ElMessageBox.confirm(
      '确认要删除该数据吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
  }
  async function queryList(params: any) {
    setLoading(true)
    try {
      const { data } = await carbonEmissionFactorApi.queryList({
        ...params,
        pageNumber: pagination.pageNumber,
        pageSize: pagination.pageSize,
      })

      setTableData(data.records)
      pagination.total = data.total
    }
    catch (e) {
    }
    finally {
      setLoading(false)
    }
  }

  async function del(ids?: number[]) {
    const res = await confirmDel().catch(() => {})
    if (res !== 'confirm' || !ids)
      return false
    try {
      await carbonEmissionFactorApi.deleteByIds(ids)
      ElMessage.success('删除成功')
      return true
    }
    catch (e) {}
  }

  return {
    loading,
    columns,
    tableData,
    pagination,
    setLoading,
    setTableData,
    queryList,
    del,
  }
}
